#/usr/bin/python
import redis
import threading
import time
import  mqClientStat

class StatTimer:
    def __init__(self,r):
        self.NodeInfo = 'machineInfo'
        self.stat = mqClientStat.mqClientStat()
        self.iplist = self.stat.get_netcard()
        self.r = r

    def refresh(self):
        info = {}
        for  item  in ('MemUsed','MemTotal','MemFree','Buffers','Cached'):
            info[item] =  self.stat.getMemory()[item]
        info['loadarv'] = self.stat.getCPUstate(1)


        for  ip in self.iplist:
            print ip[1]
            r.hset(self.NodeInfo, ip[1], info)
        global Refreshtimer
        Refreshtimer = threading.Timer(1, self.refresh)
        Refreshtimer.start()

    def keepAlive(self):
        for  ip  in  self.iplist:
            r.set(ip[1],"Connect",ex=30)
        global Keeptimer
        Keeptimer = threading.Timer(0.5, self.keepAlive)
        Keeptimer.start()

    def start(self):
        # keep Alive
        Keeptimer = threading.Timer(0.5, self.keepAlive)
        Keeptimer.start()
        # refresh
        Refreshtimer = threading.Timer(1,self.refresh)
        Refreshtimer.start()

if __name__ == '__main__':
    pool = redis.ConnectionPool(host='localhost',port=6379, db=0)
    r = redis.StrictRedis(connection_pool=pool)
    st = StatTimer(r)
    st.start()
    print "Start : %s" % time.ctime()
    time.sleep(10000)
    print "End : %s" % time.ctime()
    r.set('foo', 'bar')